#include <p18f25k20.h>
#include "SPI_Functions.h"



//--------------------------------------------------------------------------
//		SPI Functions
//--------------------------------------------------------------------------


/* Initializes the SPI to be used in the 4-wire configuration */
void SPI_init(void)
{

    SSPSTATbits.SMP = 1;         //Input data sampled at end of data output time
                                 // (even though data input is not used in this project)
    SSPSTATbits.CKE = 1;         //Transmit occurs on falling edge of SCLK

    SSPCON1bits.WCOL = 0;
    SSPCON1bits.SSPOV = 0;
    SSPCON1bits.SSPEN = 1;          //Enables the serial port pins
                                    //  and configures them as SPI pins
    SSPCON1bits.CKP = 0;            //SCLK idle state is low
    //SSPCON1bits.SSPM = 0b0010;      //SPI Master mode, clock = Fosc/64
    SSPCON1bits.SSPM = 0b0001;      //SPI Master mode, clock = Fosc/16
    //SSPCON1bits.SSPM = 0b0011;      //SPI Master mode, clock = TMR2/2

    LCD_CS = 0;                     //Chip Select is low to start


    return;
}




void SPI_write(unsigned char data)
{
    unsigned char dummy_read = 0;

    LCD_CS = 0;                 //Chip Select low

    SSPBUF = data;              //Load the new transmit data into the
                                // transmit buffer to go out to the part


    while(!SSPSTATbits.BF);     //Wait here until a recieve is complete...
                                //  even though the receive function is not used,
                                //  you have to wait before you re-load the SSPBUF
                                //  register until after you read the buffer.
                                // Otherwise the Write collision bit is set

    dummy_read = SSPBUF;        //Do a dummy read

    LCD_CS = 1;                 //Set Chip Select back high


    return;
}